import logging
import os
import subprocess
import sys

logger = logging.getLogger("FileUtil")


class FileUtil:

    @staticmethod
    def open_file_directory(path):
        """打开文件所在目录（支持文件和文件夹）"""
        try:
            if os.path.isfile(path):
                # 打开文件所在目录并选中文件
                folder = os.path.dirname(path)
                subprocess.Popen(f'explorer /select,"{path}"')
            elif os.path.isdir(path):
                # 直接打开目录
                os.startfile(path)
            else:
                logger.warning(f"路径不存在: {path}")
        except Exception as e:
            logger.error(f"打开目录失败: {str(e)}")

    @staticmethod
    def resource_path(relative_path):
        """获取资源绝对路径，兼容开发环境和PyInstaller打包环境"""
        try:
            # PyInstaller创建的临时文件夹路径
            base_path = sys._MEIPASS
        except AttributeError:
            base_path = os.path.abspath(".")

        return os.path.join(base_path, relative_path)
